package com.ruoyi.ora.service.impl;

import cn.hutool.core.convert.Convert;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.androidpublisher.AndroidPublisher;
import com.google.api.services.androidpublisher.model.ProductPurchase;
import com.ruoyi.common.utils.bean.Builder;
import com.ruoyi.ora.domain.*;
import com.ruoyi.ora.mapper.DeviceMapper;
import com.ruoyi.ora.mapper.MemberLevelMapper;
import com.ruoyi.ora.mapper.OrderMapper;
import com.ruoyi.ora.service.IGooglePaymentService;
import com.ruoyi.system.mapper.SysUserMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.FileInputStream;
import java.util.Collections;
import java.util.Date;

@Service
public class GooglePaymentServiceImpl implements IGooglePaymentService {
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private MemberLevelMapper memberLevelMapper;
    @Resource
    private DeviceMapper deviceMapper;

//    private String credentialFilePath;

    @Override
    public GooglePaymentVerificationResponse verifyPurchase(String productId, String purchaseToken, String packageName, String appName) {

        try {
// 1. 初始化Google API客户端
            HttpTransport transport = new NetHttpTransport();
            JsonFactory jsonFactory = GsonFactory.getDefaultInstance();


            // 2. z
            GoogleCredential credential = GoogleCredential
                    .fromStream(new FileInputStream("D://client_secret_955391035960-83u7t7vucqsrqdtg80fkfuq2f70b438j.apps.googleusercontent.com.json"))
                    .createScoped(Collections.singleton(
                            "https://www.googleapis.com/auth/androidpublisher"));

            // 3. 创建Android Publisher客户端
            AndroidPublisher publisher = new AndroidPublisher.Builder(
                    transport, jsonFactory, credential)
                    .setApplicationName(appName)
                    .build();

            // 4. 执行验证请求
            AndroidPublisher.Purchases.Products.Get request =
                    publisher.purchases().products()
                            .get(packageName, productId, purchaseToken);

            ProductPurchase purchase = request.execute();

            // 5. 返回验证结果
            return new GooglePaymentVerificationResponse(
                    purchase.getPurchaseState() == 0, // 0表示支付成功
                    purchase.getOrderId(),
                    purchase.getPurchaseTimeMillis());
        }catch (Exception e){
            e.printStackTrace();
        };

        return null;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateUserMembership(PaymentVerificationRequest request) {
        try {
            Order order = orderMapper.selectOneOrder(Builder.of(Order::new).with(Order::setId, Convert.toLong(request.getOrderId())).build());
            if (order != null) {
                MemberLevel memberLevel = memberLevelMapper.selectOneMemberLevel(Builder.of(MemberLevel::new).with(MemberLevel::setId, order.getProductId()).build());
                if (memberLevel != null) {
                    // 剩余时长  不限-1
                    long surplusDuration = memberLevel.getThaliDuration();
                    // 总流量
                    long totalSize = memberLevel.getThaliSize();
                    // 产品id
                    long productId = order.getProductId();
                    // 充值时间
                    Date changeTime = new Date();
//                    // 更新用户会员信息
//                    sysUserMapper.updateUser(Builder.of(SysUser::new)
//                            .with(SysUser::setUserId, order.getUserId())
//                            // 这里假设会员时长需要累加，根据实际业务调整
//                            .with(SysUser::setSurplusDuration, surplusDuration)
//                            .with(SysUser::setTotalSize, totalSize)
//                            .with(SysUser::setProductId, productId)
//                            .with(SysUser::setChangeTime, changeTime)
//                            .build());

                    deviceMapper.updateDevice(Builder.of(Device::new)
                            .with(Device::setId, order.getDeviceId())
                            // 这里假设会员时长需要累加，根据实际业务调整
                            .with(Device::setSurplusDuration, surplusDuration)
                            .with(Device::setTotalSize, totalSize)
                            .with(Device::setProductId, productId)
                            .with(Device::setChangeTime, changeTime)
                            .build());
                }
            }
        }catch (Exception e){
            throw new RuntimeException(e.getMessage());
        }

    }


    public static void main(String[] args) {
        try {

            String appName = "oramemo";


            String packageName = "com.oramemo.oramemo";
            String productId = "vip_onemonth";
            String purchaseToken = "jjilaclhhihimempaklblgah.AO-J1Oxt121uzxI0ct2GVm8bIPrx7NYwc76hMTXnJtnL8wp6WCyhksoHDS_pCCpWbMy8B1_EbU69ZiRvpDEeha9QPHticYhM8A";


            // 1. 初始化Google API客户端
            HttpTransport transport = new NetHttpTransport();
            JsonFactory jsonFactory = GsonFactory.getDefaultInstance();


            // 2. z
            GoogleCredential credential = GoogleCredential
                    .fromStream(new FileInputStream("D://client_secret_955391035960-83u7t7vucqsrqdtg80fkfuq2f70b438j.apps.googleusercontent.com.json"))
                    .createScoped(Collections.singleton(
                            "https://www.googleapis.com/auth/androidpublisher"));

            System.out.println("111");

            // 3. 创建Android Publisher客户端
//            AndroidPublisher publisher = new AndroidPublisher.Builder(
//                    transport, jsonFactory, credential)
//                    .setApplicationName(appName)
//                    .build();
//
//            // 4. 执行验证请求
//            AndroidPublisher.Purchases.Products.Get request =
//                    publisher.purchases().products()
//                            .get(packageName, productId, purchaseToken);
//
//            ProductPurchase purchase = request.execute();
//
//            // 5. 返回验证结果
//            GooglePaymentVerificationResponse googlePaymentVerificationResponse = new GooglePaymentVerificationResponse(
//                    purchase.getPurchaseState() == 0, // 0表示支付成功
//                    purchase.getOrderId(),
//                    purchase.getPurchaseTimeMillis());
//
//            System.out.println(googlePaymentVerificationResponse);
        }catch (Exception e){
            e.printStackTrace();
        };
    }
}
